﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BFlatCompile.Nodes
{
	public class ForeachLoop : Executable
	{
		public Expression List { get; private set; }
		public Variable Iterator { get; private set; }
		public Executable[] Code { get; private set; }

		private ForeachLoop(Expression list, Token iterator, Executable[] lines)
		{
			this.List = list;
			this.Iterator = new Variable(iterator.Value, iterator);
			this.Code = lines;
		}

		public static ForeachLoop ParseForeach(Tokens tokens)
		{
			tokens.PopExpected("foreach");
			tokens.PopExpected("(");
			tokens.PopIdentifier();
			Token iterator = tokens.PreviousToken();
			tokens.PopExpected("in");
			Expression list = Expression.Parse(tokens);
			tokens.PopExpected(")");
			Executable[] lines = CodeBlock.Parse(tokens, false);
			return new ForeachLoop(list, iterator, lines);
		}

		public override void ResolveCode(Class c, Dictionary<object, object> parents)
		{
			this.List.ResolveCode(c, parents);
			foreach (Executable exec in this.Code)
			{
				exec.ResolveCode(c, parents);
			}

			// TODO: as this is an assignment operator of sorts, must verify that this.Iterator.Name is not the name of a member
		}

		public override void ResolveClassToThis(Class c)
		{
			this.List.ResolveClassToThis(c);

			foreach (Executable ex in this.Code)
			{
				ex.ResolveClassToThis(c);
			}
		}
	}
}
